﻿@inject IJSRuntime jsRuntime

<form @onsubmit="AddTask">
    <div class="input-group">
        <input type="text" class="form-control" placeholder=@Label aria-label=@Label
               @bind="NewTaskValue" @ref="_inputRef" />
        <div class="input-group-append">
            <button class="btn btn-secondary" type="submit">Add task</button>
        </div>
    </div>
</form>
<ol class="list-group">
    @foreach (var item in Items)
    {
        @ItemsTemplate(item);
    }
</ol>
@code {
    private ElementReference _inputRef;
    private string NewTaskValue { get; set; } = string.Empty;
    private IEnumerable<Todo> _todos = Array.Empty<Todo>();

    [Parameter] public string Label { get; set; } = "Task description";
    [Parameter] public RenderFragment<Todo> ItemsTemplate { get; set; } = default!;
    [Parameter] public IEnumerable<Todo> Items { get => _todos; set => _todos = value ?? Array.Empty<Todo>(); }
    [Parameter] public EventCallback<Todo> OnAddingTodo { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await jsRuntime.InvokeVoidAsync("document.body.focus.call", _inputRef);
        }
    }

    private void AddTask()
    {
        if (!string.IsNullOrWhiteSpace(NewTaskValue))
        {
            OnAddingTodo.InvokeAsync(new Todo { Text = NewTaskValue });
        }
        NewTaskValue = string.Empty;
    }
}
